/**
 * 自定义webpack插件
 * @author: Merjiezo
 * @since: 2020-01-08
 * @version: 1.0.0
 */
const { ConcatSource } = require('webpack-sources')

class CustomPlugin {
  constructor(options) {
    this.options = options
  }

  apply(compiler) {
    const options = this.options
    compiler.hooks.make.tap('CustomPlugin', (compilation) => {
      compilation.hooks.optimizeChunkAssets.tap('CustomPlugin', (chunks) => {
        // console.log(chunks);
        for (const chunk of chunks) {
          // 没有 chunk.name 的是分块文件
          if (!chunk.name) {
            continue
          }
          for (const file of chunk.files) {
            let filename = file
            const data = {
              chunk,
              filename
            }

            var top = options.top
            var bottom = options.bottom
            const topObj = compilation.getPath(top, data)
            const endObj = compilation.getPath(bottom, data)
            compilation.updateAsset(file, (old) => {
              var value = topObj + old.source() + endObj
              let newSource = new ConcatSource(value)
              return newSource
            })
          }
        }
      })
    })
  }
}

module.exports = CustomPlugin
